package com.mqy.config;
/**
 * This file created by mengqingyi on 2018/7/10.
 */

import org.apache.phoenix.jdbc.PhoenixConnectionPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author mengqingyi
 * @classDescription 阿里phoenix自建连接池
 * @create 2018-07-10 18:57
 **/
@Configuration
public class PhoenixConnectionByAliPool {
    /**
     * 日志
     */
    //private static final Logger logger = LoggerFactory.getLogger(PhoenixConnectionByAliPool.class);

    //@Value("ZK_ADDRESS_DEBUG")
    String ZK_ADDRESS_DEBUG = "jdbc:phoenix:192.168.1.108" ;

    static PhoenixConnectionPool aLiPool = null;
    /**
     * 从阿里 PhoenixConnectionPool 获取连接
     */
    @Bean
    public PhoenixConnectionPool getAliPhoenixConnectionPool() {
        if(null==aLiPool){
            aLiPool = new PhoenixConnectionPool(ZK_ADDRESS_DEBUG);
        }
        return aLiPool;
    }

    /**
     * 依次关闭资源
     *
     * @param connection 连接
     * @param statement  准备语句
     * @param resultSet  结果集
     */
    public static Boolean close(Connection connection, PreparedStatement statement, ResultSet resultSet) {
        Boolean flag = Boolean.TRUE;
        if (null != resultSet) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                flag = Boolean.FALSE;
                //logger.error("[PhoenixConnectionByJDBC]结果集rs关闭异常");
                e.printStackTrace();
            }
        }

        if (null != statement) {
            try {
                statement.close();
            } catch (SQLException e) {
                flag = Boolean.FALSE;
                //logger.error("[PhoenixConnectionByJDBC]准备语句pstmt关闭异常");
                e.printStackTrace();
            }
        }
        if (null != connection) {
            try {
                aLiPool.close();
            } catch (SQLException e) {
                flag = Boolean.FALSE;
                //logger.error("[PhoenixConnectionByJDBC]连接conn关闭异常");
                e.printStackTrace();
            }
        }
        return flag;
    }

}
